import React, { memo } from 'react';
import { connect } from 'react-redux';
import { Select } from 'antd';
import styles from './index.less';
import { astUtil, findNodeById } from '@/utils';

export function EventProp(props: API.IEvent) {
  const { name, classProps, onChange, value } = props;

  return (
    <dl className={styles.event}>
    {name && <dt>{name}</dt>}
      <Select
        className={styles.eventSelect}
        size="small"
        showSearch
        onChange={(value: string) => onChange && onChange(value)}
        value={value}
      >
        {
          classProps
            .filter((item: API.IClassProp) => item.name !== 'constructor')
            .map((item: API.IClassProp) => <Select.Option key={item.name} value={item.name}>{item.name}</Select.Option>)}
      </Select>
    </dl>
  );
}

function EventProps(props: API.IEvents) {
  const { project: { ast, currentCompId, pageConfig }, saveNodeChange } = props;
  const classProps = astUtil.getClassEventsByAst(ast);
  const currentNode: API.Node | undefined = findNodeById(pageConfig, currentCompId);
  const handleEventChange = (event: string, func: string) => {
    if (!currentNode) return;
    if (!currentNode.events) currentNode.events = {};
    currentNode.events[event] = func;
    saveNodeChange({ payload: currentNode });
  };
  return (
    <EventProp name="点击" event="onClick" onChange={handleEventChange} classProps={classProps} value={currentNode?.events?.onClick}/>
  );
}

export default connect(
  ({ project }: any) => ({ project }),
  {
    saveNodeChange: ({ payload }: any) => ({ type: 'project/saveNodeChange', payload })
  }
)(memo(EventProps));